+function($) {
    var time;
    var storage  = $.localStorage,
        playlist = storage.get('playlist') || [],
        setting  = storage.get('setting') || {},
        bundle   = false;

    var player   = new jPlayerPlaylist(
      {
        jPlayer: "#jplayer",
        cssSelectorAncestor: "#jp_container"
      },
      playlist,
      {
        playlistOptions: {
          enableRemoveControls: true
        },
        loop: setting.repeat,
        swfPath: "js/jPlayer",
        supplied: "webmv, webma, ogv, oga, m4v, m4a, mp3",
        smoothPlayBar: true,
        keyEnabled: true,
        audioFullScreen: false
      }
    );



    $('#jplayer').bind($.jPlayer.event.ready, function() {
      if( playlist.length && setting.currentIndex > -1 ){
          player.select(setting.currentIndex);
          $(this).jPlayer("playHead", setting.percent);
          setting.play && $(this).jPlayer("play", setting.currentTime);
          setting.volume && $(this).jPlayer( "volume", setting.volume );
          setting.shuffle && player.shuffle(true);
          updateDisplay();
      }
      setupListener();

    });

    // setup Listener
    function setupListener(){
      $('#jplayer').bind($.jPlayer.event.timeupdate, function(event){
        setting.currentTime = event.jPlayer.status.currentTime;
        setting.duration = event.jPlayer.status.duration;
        setting.percent = event.jPlayer.status.currentPercentAbsolute;
        setting.currentIndex = player.current;
        setting.shuffle = player.shuffled;
        updateSetting();
        updatemusiccover();
        lrcscroll();  //歌曲播放当前时间初始化  歌词插件
        lrcstart();   //歌曲开始播放初始化 歌词插件
      })
      .bind($.jPlayer.event.pause, function(event){
        setting.play = false;
        updateSetting();
        updateDisplay();
      })
      .bind($.jPlayer.event.play, function(){
        setting.play = true;
        updateSetting();
        updateDisplay();
      })
      .bind($.jPlayer.event.repeat, function(event){
        setting.repeat = event.jPlayer.options.loop;
        updateSetting();
      })
      .bind($.jPlayer.event.volumechange, function(event){
        setting.volume = event.jPlayer.options.volume;
        updateSetting();
      })


      // remove item from player gui
      $(document).on('click', '.jp-playlist-item-remove', function(e){
        window.setTimeout(updatePlaylist, 500);
      });

    };

    /**
     *  歌词滚动
     *  Xiaoya
     *  2016-4-4 22:22:13
     */
    // 歌词初始化
    lrcinitialize = function(){
      $.lrc.init($('#lrc_content').val());
    };

    // 输出当前的播放时间
    lrcscroll = function(event){
      //console.log('输出当前播放时间'+setting.currentTime);
      if(setting.currentTime == 0){
        time = "";
      }else {
        time = setting.currentTime;
        //console.log('我是播放：'+time);  //播放的时候输出
      }
    };

    // 开始播放 歌词开始  点击开始方法调用lrc。start歌词方法 返回时间time
    lrcstart = function(event){
      if($('#lrc_content').val()!==""){
        $.lrc.start(function(){
          return time;
        });
        if(typeof($('#lrc_content').val()) == "undefined"){ //判断如果不在收藏音乐页面 则暂停歌词
          $.lrc.stop();
        }
      }else{
        $(".contentlrc").html("暂无歌词");
      }
      //console.log('歌词开始滚动'+$('#lrc_content').val());
    };

    /*
    *   判断移动端和PC端
    *   2017-11-15 00:58:06
    *   yyyvy
    * */
    if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
      console.log('This is iphone');
    } else {
      console.log('This is PC');
    }


    // bind click on play-me element.
    $(document).on('click', '.play-me', function(e){
      var id = $(this).attr("data-id");
      var i = inObj(id, playlist);
      if( i == -1){
        $.ajax({
           type : "get",
           dataType : "json",
           url : ajax_object.ajaxurl,
           data : {action: "get_media", id : id},
           success: function(obj) {
              if(obj.length == 1){
                player.add( obj[0], true );
                updatePlaylist();
                updatemusiccover();
              }else if(obj.length > 1){
                player.setPlaylist(obj);
                player.play(0);
                updatePlaylist();
                updatemusiccover();
              }
           }
        });
      }else{
        if( player.current == i ){
          setting.play ? player.pause() : player.play();
        } else {
          player.play( i );
        }
      }
    });


    /**
     *  删除列表所有歌曲  Del ListTab all music.
     *  2016-4-3 07:38:02
     */
    $(document).on('click', '.playlisttrashall', function(e) {
        if(confirm("确定删除列表的所有音乐？")){
            player.remove();
            updatePlaylist();
        }
        return;
    });

    // update Music Cover
    updatemusiccover = function(){
        if(playlist[player.current] == undefined){
            return;
        }else{
            $('.mymusic_pic').attr('src',playlist[player.current].poster);
            $('.mymusic_title').html(playlist[player.current].artist);
            $('.mymusic_username').html('101,400 <br>'+playlist[player.current].username);
            $('.mymusic_lyric').html(playlist[player.current].lyric);
            return;
        }
    }


    /**
     * update Article songs
     * 判断是否进入文章页面，如果进入播放页面，就播放文章歌曲，开启单曲循环
     * 判断当前播放是否是文章音乐，如果是
     * 再判断判断当前是否有文章播放按钮
     * 都不成立就关闭单曲循环
     * 2016-4-3 07:38:11
     */
    updateArticleSongs = function(){
        if(playlist[player.current] == undefined){
            return;
        }else {
            if (playlist[player.current].id == $('.detail_play').attr("data-id")) {
                $('.jp-repeat').trigger("click");
            } else if ($('.detail_play').length > 0) {
                $('.detail_play').trigger("click") && $('.jp-repeat').trigger("click");
            } else {
                $('.jp-repeat-off').trigger("click");
            }
            ;
        };
    };


    // update ui
    updateDisplay = function(){
      $('.play-me').removeClass('active');
      $('.play-me').parent().removeClass('active');
      if( playlist[player.current] ){
        var current = $('a[data-id='+playlist[player.current]['id']+']'+', '+'a[data-id='+playlist[player.current]['ids']+']');
          if(current.parent().hasClass('my-music-collect')){
              setting.play ? current.addClass('active')&&current.parent().addClass('active') : current.removeClass('active')&&current.parent().removeClass('active');
              updatemusiccover();
          }else{
              setting.play ? current.addClass('active') : current.removeClass('active');
              updatemusiccover();
          }
      }


      lrcinitialize();  //初始化歌词  歌词插件
    };





    // update setting 
    function updateSetting(){
      storage.set( 'setting', setting );
    };

    // update playlist
    function updatePlaylist(){
      updateDisplay();
      playlist = player.playlist;
      storage.set( 'playlist', playlist );
    };

    // check exist
    function inObj(id, list) {
        var i;
        for (i = 0; i < list.length; i++) {
            if ( (list[i]['id'] == id) || (list[i]['ids'] == id) ) {
                return i;
            }
        }
        return -1;
    };




}(jQuery);